# Author: slowchen
# Time: 2019/7/9 13:55
# Description: 执行测试，可执行所有测试用例，或者执行case_list.txt里面的指定测试用例
# TODO:

import time
import unittest
from test_lib.HTMLTestRunnerChart import HTMLTestRunner
from test_lib.case_loader import *
from test_lib.logger import *
from test_lib.suite_loader import SuiteLoader

suite_loader = SuiteLoader()


def get_suite(test_suite):
    # 将所有的测试用例加载到一个无嵌套的TestSuite中
    # 由于使用SuiteLoader里面load_suite()组装的TestSuite是按文件夹目录多级嵌套的，我们把所有用例取出，放到一个无嵌套的TestSuite中，方便之后操作

    suite = unittest.TestSuite()

    def _collect(tests):  # 递归，如果下级元素还是TestSuite则继续往下找
        if isinstance(tests, unittest.TestSuite):
            if tests.countTestCases() != 0:
                for i in tests:
                    _collect(i)
        else:
            suite.addTest(tests)  # 如果下级元素是TestCase，则添加到TestSuite中

    _collect(test_suite)
    for case in suite:
        log_debug(case.id())
    return suite


def all_suite():
    return get_suite(suite_loader.load_suite(get_all_case_files()))


def customize_suite():
    return get_suite(suite_loader.load_suite(get_customize_case_files()))


def run(suite):
    # 运行suite，具体运行哪些，根据传进来的suite决定
    date = time.strftime('%Y%m%d', time.localtime(time.time()))
    with open(config.report_file, 'wb') as fp:
        HTMLTestRunner(stream=fp,
                       title='[{}] 卜卜游接口测试报告'.format(date),
                       tester='程杰',
                       verbosity=2,
                       description='每日定时接口测试，监控线上接口情况').run(suite)


def run_all():
    # 运行所有case目录下的测试用例
    run(all_suite())


def run_customize():
    # 运行自定义的测试用例
    run(customize_suite())


if __name__ == '__main__':
    run_customize()
